<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateLiftPoleAPIRequest;
use App\Http\Requests\API\UpdateLiftPoleAPIRequest;
use App\Models\{LiftPole,ParkInfo,OfflineUser};
use App\Repositories\LiftPoleRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

/**
 * Class LiftPoleController
 * @package App\Http\Controllers\API
 */

class LiftPoleAPIController extends AppBaseController
{
    /** @var  LiftPoleRepository */
    private $liftPoleRepository;

    public $verify_arr = [
        0=>'未审核',
        1=>'已通过',
        2=>'未通过',
    ];
    private $park_arr = [];


    public function __construct(LiftPoleRepository $liftPoleRepo)
    {
        $this->liftPoleRepository = $liftPoleRepo;
        $park_arr = $this->getUserParks();
        $park_arr = $this->getParkCodes($park_arr);
        $this->park_arr = $park_arr;
    }

    /**
     * Display a listing of the LiftPole.
     * GET|HEAD /liftPoles
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $input = $request->all();
        $page = $request->input("page",1);
        $pages = $request->input("limit",15) ;
        $liftPoles = $this->liftPoleRepository->paginate($request->limit);
        $p = LiftPole::select("*");
        if(isset($input['vpl_number']) && !empty($input['vpl_number'])){
            $p = $p->where("vpl_number",strtoupper($input['vpl_number']));
        }
        if(isset($input['is_verify']) && is_numeric($input['is_verify'])){
            $p = $p->where("is_verify",$input['is_verify']);
        }
        // 获取车场范围
        if (isset($input['park_code']) && !empty($input['park_code'])) {
            $p = $p->whereIn("park_code",$input['park_code']);
        } else {
            $p = $p->whereIn("park_code", $this->park_arr);
        }
        // 补录时间
        if(isset($input['out_time']) && !empty($input['out_time'])) {
            $atime = $input['out_time'];
            if (isset($atime[0]) && !empty($atime[0])) {
                $start_time = $atime[0];
                $p = $p->where("out_time", '>=', $start_time);
            }
            if (isset($atime[1]) && !empty($atime[1])) {
                $start_time = $atime[1];
                $p = $p->where("out_time", '<=', $start_time);
            }
        }
        $file_name = md5('lift_pole_'.json_encode($input)).".csv";
        if(isset($input['export']) && !empty($input['export'])) {
            if(file_exists(storage_path("app/public/".$file_name))){
                $res = [];
                $res['file_name'] = $file_name;
                return   $this->sendResponse($res, '查询成功');
            }
            $liftPoles = $p->orderBy('id','desc')->get();
        } else {
            $liftPoles = $p->orderBy('id','desc')->paginate($pages, array("*"), "page", $page);
        }
        $type_arr = config('custom.auth_type');
        foreach ($liftPoles as &$val) {
            $park_name = ParkInfo::where("park_code",$val->park_code)->value("parking_name");
            $val->park_name = $park_name?$park_name:'';
            $val->parking_charge = $val->parking_charge/100;
            $val->verify_name = isset($this->verify_arr[$val->is_verify])?$this->verify_arr[$val->is_verify]:'';
            $val->in_time = $val->in_time?date("Y-m-d H:i:s", $val->in_time):'';
            $val->out_time = $val->out_time?date("Y-m-d H:i:s", $val->out_time):'';
            $val->in_img = config('custom.file_car_img_url').'/'.$val->park_code.'/'.$val->record_id.'_'.$val->status.'.jpg';
            $val->park_duration = sec2time($val->parking_duration);
            $val->calc_charge	 = re2float($val->calc_charge/100);
            $val->vpl_type = isset($type_arr[$val->vpl_type])?$type_arr[$val->vpl_type]:'';
            $val->charger = '';
            $val->seq_num = '';
            if($val->charge_items) {
                foreach ($val->charge_items as $v) {
                    if($v['charge_type'] == 8) {
                    $charger = OfflineUser::where("name", $v['charger']??'')->value("true_name");
                    $val->charger .= $charger ? $charger . ":" . $v['charger'] : $v['charger'] . ";";
                    $val->seq_num .= $v['seq_num'] ?  unicodeDecode(str_replace('u','\u',$v['seq_num'])). ";" : '' ;
                    }
                }
                $val->charger = trim($val->charger, ";");
                $val->seq_num = trim($val->seq_num, ";");
            }
        }

        $file_name = md5('lifpole_'.json_encode($input)).".csv";
        if(isset($input['export']) && !empty($input['export'])){
            $title = ['vpl_number'=>'车牌号码','park_name'=>'车场名称','vpl_type'=>'授权类型','in_time'=>'进场时间','out_time'=>'出场时间','park_duration'=>'停车时长','calc_charge'=>'应收金额(元)','charger'=>'收费员','verify_name'=>'审核状态','seq_num'=>'抬杆理由'];
            $export_data = [];
            foreach ($liftPoles as $val) {
                $tmp = [];
                $tmp['vpl_number'] = $val->vpl_number;
                $tmp['park_name'] = $val->park_name;
                $tmp['vpl_type'] = $val->vpl_type;
                $tmp['in_time'] = $val->in_time.' ';
                $tmp['out_time'] = $val->out_time.' ';
                $tmp['park_duration'] = $val->parking_duration;
                $tmp['calc_charge'] = $val->calc_charge;
                $tmp['charger'] = $val->charger;
                $tmp['verify_name'] = $val->verify_name;
                $tmp['seq_num'] = $val->seq_num;
                $export_data[] = $tmp;
            }
            return $this->export($export_data,$title,$file_name);
        }

        return $this->sendResponse($liftPoles->toArray(), '获取成功');
    }

    /**
     * Store a newly created LiftPole in storage.
     * POST /liftPoles
     *
     * @param CreateLiftPoleAPIRequest $request
     *
     * @return Response
     */
    public function save(CreateLiftPoleAPIRequest $request)
    {
        $input = $request->all();

        $liftPoles = $this->liftPoleRepository->create($input);

        return $this->sendResponse($liftPoles->toArray(), '保存成功');
    }

    /**
     * Store a newly created LiftPole in storage.
     * POST /liftPoles
     *
     * @param CreateLiftPoleAPIRequest $request
     *
     * @return Response
     */
    public function store(CreateLiftPoleAPIRequest $request)
    {
        $input = $request->all();

        $liftPoles = $this->liftPoleRepository->create($input);

        return $this->sendResponse($liftPoles->toArray(), '保存成功');
    }

    /**
     * Display the specified LiftPole.
     * GET|HEAD /liftPoles/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        /** @var LiftPole $liftPole */
        $liftPole = $this->liftPoleRepository->findWithoutFail($id);

        if (empty($liftPole)) {
            return $this->sendError('数据不存在');
        }
        $park_name = ParkInfo::where("park_code",$liftPole->park_code)->value("parking_name");
        $liftPole->park_name = $park_name?$park_name:'';
        $liftPole->parking_charge = $liftPole->parking_charge/100;
        $liftPole->park_duration = sec2time($liftPole->parking_duration);
        $liftPole->verify_name = isset($this->verify_arr[$liftPole->is_verify])?$this->verify_arr[$liftPole->is_verify]:'';
        $liftPole->img = config('custom.file_car_img_url').'/'.$liftPole->park_code.'/'.$liftPole->record_id.'_'.$liftPole->status.'.jpg';
        $liftPole->gp_img = config('custom.file_car_img_url').'/'.$liftPole->park_code.'/'.$liftPole->record_id.'_6.jpg';

        return $this->sendResponse($liftPole->toArray(), '获取成功');
    }

    /**
     * Update the specified LiftPole in storage.
     * PUT/PATCH /liftPoles/{id}
     *
     * @param  int $id
     * @param UpdateLiftPoleAPIRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $input = $request->all();

        /** @var LiftPole $liftPole */
        $liftPole = $this->liftPoleRepository->findWithoutFail($id);

        if (empty($liftPole)) {
            return $this->sendError('数据不存在');
        }

        $liftPole = $this->liftPoleRepository->update($input, $id);

        return $this->sendResponse($liftPole->toArray(), '更新成功');
    }

    /**
     * Remove the specified LiftPole from storage.
     * DELETE /liftPoles/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        /** @var LiftPole $liftPole */
        $liftPole = $this->liftPoleRepository->findWithoutFail($id);

        if (empty($liftPole)) {
            return $this->sendError('数据不存在');
        }

        $liftPole->delete();

        return $this->sendResponse($id, '删除成功');
    }
}
